package com.yisoo.ubag.app.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.yisoo.common.constant.LoginStatusConstant;
import com.yisoo.common.utils.R;
import com.yisoo.common.vo.LoginStatusVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token != null){
            if (stringRedisTemplate.hasKey(LoginStatusConstant.APP_LOGIN_TOCKEN+token)){
                stringRedisTemplate.opsForValue().set(LoginStatusConstant.APP_LOGIN_TOCKEN+token, token,60*5, TimeUnit.SECONDS);
                return true;
            }else{
                falseResult(response,-100,"登录过期");
                return false;
            }
        }else{
            falseResult(response,-100,"未登录");
            return false;
        }
    }
    public void falseResult(HttpServletResponse response,int errorCode,String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("code", errorCode);
        res.put("msg", msg);
        response.getWriter().append(res.toString());
    }
}
